package com.loren.demo04.publish_subscribe.subscriber;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

@Slf4j
@Component
public class MessageSubscriber {

    public static final String CHANNEL_NAME = "test-channel";

    /**
     * 发布订阅模式 - 订阅
     * 订阅的客户端都能收到消息
     */
    public MessageSubscriber(RedisConnectionFactory redisConnectionFactory) {
        RedisConnection redisConnection = redisConnectionFactory.getConnection();
        redisConnection.subscribe((message, pattern) -> {
            log.info("message = {}", message);
            log.info("pattern = {}", pattern);
        }, CHANNEL_NAME.getBytes(StandardCharsets.UTF_8));
    }
}
